#
#  Change	Date		Author			Description
# --------------------------------------------------------------------------------------------------------
#   001	        07-12-2013	Adam Dosch		Updated database collection creation to include
#                                                       packagename, ostype and arch instead of just the
#                                                       packagename and ostype
#   002         07-13-2013      Adam Dosch              Adding init option to Connection class to distinguish
#                                                       between what kind of RBS connection type we want to
#                                                       use.
#                                                       Removing 'dbtype' from Connection class -- we are
#                                                       always goign to use MongoDB capped collections + tailing
#   003         07-14-2013      Adam Dosch              Adjusted queue capped collection size based on rough
#                                                       document size of 132 bytes
#   004         08-15-2013      Adam Dosch              Re-adjustmenet of queue capped collection to only hold
#                                                       a hard-coded limit of 3000 before roll-over

import sys

import pymongo

from pymongo import errors as mongoErrors

class Connection:
    
    def __init__(self, conntype, server="localhost", port=27017, db="rbs"):
        """
        Connect to RBS MongoDB database
            conntype = RBS connection type: websvc or builder
            server = MongoDB server, default: localhost
            port = MongoDB port, default: 27017
            db = MongoDB database, default: rbs
        """
            
        # Init server/port/dbname
        self.dbserver = server
        self.dbport = port
        self.dbname = db
  
        # Init of db connection object handle
        self.conn = pymongo.MongoClient(host=self.dbserver, port=self.dbport, auto_start_request=False, safe=True, j=True, w=1)
        
        # Init of db object handle
        self.db = self.conn[self.dbname]
        
        # if conntype is 'web', that's where we want to auto-create databases + indexes if they don't exist.
        if conntype.lower() == "web":
            
            # Create collections (if need be)
            for collection in ['queue', 'builds', 'heartbeat']:
                self.createCollection(collection)
            
                # Build up indexes (if need be)
                if self.buildIndex(collection) == None:
                    print "'%s' collection index already created or exists" % collection
                else:
                    print "'%s' collection index successfully created" % collection
            
    def createCollection(self, collName):
        try:
            # After light analysis, the average queue doc
            # size is: 134 bytes
            #
            # Use to byte figure above to calculate the max
            # documents + size (in bytes, as well)
            #
            # Note: DataTables UI can handle around 10K records before it becomes
            # a problem the way I have it working.  FYI.
            #
            # 25,000 queued build reqs x 134 bytes = 3,350,000 (~3.4MB)
            #  3,000 queued build reqs x 134 bytes =   420,000 (~0.4MB)
            #
            
            if collName == "queue":
            
                self.db.create_collection(collName, capped=True, max=3000, size=420000)
            else:
                self.db.create_collection(collName)
            
            print "Mongo collection '%s' created successfully" % collName
        except mongoErrors.CollectionInvalid:
            print "Warning: '%s' collection already exists, oh well." % collName
        except mongoErrors.OperationFailure, e:
            print "Error: Ooo, big shitty shitty!  %s" % e
        
    def buildIndex(self, collName):
        c = self.db[collName]
        
        # Creating index based on collection
        if collName == "queue":
            queue = self.db[collName]
            return c.ensure_index([('package', pymongo.ASCENDING),('ostype', pymongo.ASCENDING), ('arch', pymongo.ASCENDING)], unique=True, cache_for=300)
        elif collName == "builds":
            return c.ensure_index([('package', pymongo.ASCENDING)], cache_for=300)
        else:
            return None
    
#def main():
#    try:
#       c = DBConnect()
#    except mongoErrors.ConnectionFailure, e:
#        print "Exception: %s" % (e)

#if __name__ == '__main__':
#    main()

